# -*- coding: utf-8 -*-
from jqdatasdk import *
import time
import pymongo
from apscheduler.schedulers.blocking import BlockingScheduler
from mongo_config import *
from datetime import datetime, date, timedelta

mongo_client = pymongo.MongoClient(MONGO_URL_TEST, 27017)
db = mongo_client[MONGO_DB_RES]

auth('15808201361', 'xht081624.')

def get_codes():
    codes = []
    stock_data = get_all_securities(types=['stock'], date=None)
    for code in stock_data.iterrows():
        codes.append(code[0])
    return codes

def get_data(codes):
    data_all = []
    yesterday = (date.today() + timedelta(days=-30)).strftime("%Y-%m-%d")
    today = time.strftime('%Y-%m-%d', time.localtime(time.time()))
    for code in codes:
        data_list = {}
        code_data = []
        datas = get_money_flow(code, start_date=yesterday, end_date=today)[-5:]
        for index, datum in datas.iterrows():
            dicts = {}
            dicts['time'] = int(time.mktime(time.strptime(str(datum['date']), "%Y-%m-%d %H:%M:%S")))
            dicts['net_amount_main'] = datum['net_amount_main']
            # dicts['net_amount_small'] = datum['net_amount_m'] + datum['net_amount_s']
            dicts['net_amount_small'] = datum['net_amount_s']
            code_data.append(dicts)
        data_list['_id'] = code[:-5]
        data_list['data'] = code_data
        data_all.append(data_list)
    return data_all

def save_to_mongo(datas):
    collection_res = db['flow']
    try:
        collection_res.remove()
        collection_res.insert_many(datas, ordered=False)
        print('insert ok!')
    except Exception as e:
        print(e)

# 统计资金流向数据
def main_flow():
    codes = get_codes()
    datas = get_data(codes)
    if len(datas) > 0:
        save_to_mongo(datas)

# if __name__ == '__main__':
#     main_flow()
#     # 定义BlockingScheduler
#     sched = BlockingScheduler()
#     sched.add_job(main, 'cron', day_of_week='mon-fri', hour=20, minute=30)